package com.kumarn.android.test.gcmtestsend;

import java.io.IOException;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements Runnable {

	private Button SendButton;
	private String resultMessage;
	private ProgressDialog progressDialog;
	Handler mHandler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//送信ボタン
		SendButton = (Button) findViewById(R.id.send_button);
		SendButton.setOnClickListener(sendClick);
	}

	//送信ボタンOnClickListener
	OnClickListener sendClick = new OnClickListener() {
		public void onClick(View arg0) {
			startProgress(); // プログレスダイアログ表示
			Thread thread = new Thread(MainActivity.this);
			thread.start(); // 処理開始
		}
	};

	public void run() {
		//GCMメッセージ生成
		Sender sender = new Sender(GCMSendPrefarence.API_KEY);
		Message message = new Message.Builder()
				.collapseKey("1")
				.timeToLive(3)
				.delayWhileIdle(false)
				.addData("TYPE", "FINE")
				.build();

		//メッセージ送信
		try {
			Result result = sender.send(message, GCMSendPrefarence.REGIST_ID, 3);
			resultMessage = result.getMessageId()+":"+result.getErrorCodeName();
		} catch (IOException e) {
			e.printStackTrace();
			resultMessage = e.getMessage();
		}

		//ダイアログClose
		mHandler.post(new Runnable() {
			public void run() {
				progressDialog.dismiss();
				Toast.makeText(MainActivity.this,resultMessage , Toast.LENGTH_LONG).show();
			}
		});
	}

	//処理中ダイアログ表示
	public void startProgress() {
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("処理中・・・");
		progressDialog.setIndeterminate(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();
	}

}
